import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Car } from 'src/module/admin/car/entities/car.entity';
import { Order } from 'src/module/admin/order/entities/order.entity';
import { Service } from 'src/module/admin/service/entities/service.entity';
import { User } from 'src/module/admin/user/entities/user.entity';
import { Not, Repository } from 'typeorm';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Service)
    private readonly serviceRepository: Repository<Service>,
    @InjectRepository(Car)
    private readonly carRepository: Repository<Car>,
  ) {}

  create() {
    return 'This action adds a new order';
  }

  // 根据用户ID获取他的订单情况
  async findAllOrderByUserId(
    userId: number,
    currentPage: number,
    pageSize: number,
    order_status,
    license_plate,
  ): Promise<Array<Order> | any> {
    let list = null;
    if (license_plate != '') {
      list = await this.orderRepository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.car', 'car')
        .leftJoinAndSelect('order.user', 'user')
        .leftJoinAndSelect('order.service', 'service')
        .leftJoinAndSelect('service.photos', 'photos')
        .where('user.id = :id', { id: userId })
        .andWhere('order.order_status = :order_status', {
          order_status: order_status,
        })
        .andWhere('car.license_plate = :license_plate', {
          license_plate: license_plate,
        })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    } else {
      list = await this.orderRepository.findAndCount({
        select: ['id', 'type', 'car', 'user', 'service', 'order_status'],
        relations: ['car', 'user', 'service', 'service.photos'],
        skip: (currentPage - 1) * pageSize,
        take: pageSize,
        where: { user: { id: userId }, isDelete: false, order_status },
        order: { id: 'DESC' },
      });
    }

    const result = list[0].map((item) => {
      return {
        ...item,
        car: {
          id: item.car.id,
          primaryId: item.car.primary_id,
          license_plate: item.car.license_plate,
          brand: item.car.brand,
          status: item.car.status,
        },
        user: {
          id: item.user.id,
          primaryId: item.user.primary_id,
          name: item.user.name,
        },
        service: {
          id: item.service.id,
          primaryId: item.service.primary_id,
          category: item.service.category,
          service_point: item.service.service_point,
          money: item.service.money,
          photo: item.service.photos[0] || {},
        },
      };
    });

    return {
      list: result,
      totalCount: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }

  // 用户新增添加订单
  async addOrder(userId: number, carId: number, serviceId: number) {
    const order = new Order();

    const user = await this.userRepository.findOne({
      where: { id: userId, isDelete: false },
    });
    const car = await this.carRepository.findOne({
      where: { id: carId, isDelete: false },
    });
    const service = await this.serviceRepository.findOne({
      where: { id: serviceId, isDelete: false },
    });

    if (!user || !car || !service) {
      return {
        code: 900,
        success: false,
        message: '用户或车辆或服务不存在',
      };
    }

    if (user.account - service.money < 0) {
      return {
        code: 901,
        success: false,
        message: '余额不足',
      };
    }

    await this.userRepository.update(
      { id: userId },
      { account: user.account - service.money },
    );

    const updatedUser = await this.userRepository.findOne({
      where: { id: userId, isDelete: false },
    });

    order.user = updatedUser;
    order.car = car;
    order.service = service;

    updatedUser.service = [service];
    car.service = [service];

    await this.userRepository.save(updatedUser);
    await this.carRepository.save(car);

    return await this.orderRepository.save(order);
  }

  // 完成订单
  async finish(userId, params) {
    try {
      await this.orderRepository.update(params.orderId, { order_status: '3' }); // 设置为3表示以结束
      await this.carRepository.update(params.carId, { status: '0' }); // 设置为0表示该成已经运行了
    } catch (e) {
      return {
        code: '901',
        msg: '失败',
      };
    }

    return {
      code: '900',
      msg: 'success',
    };
  }

  // 删除一个订单
  async deleted(id) {
    return this.orderRepository.update(id, { isDelete: true });
  }
}
